# @Author: 唐奇才
# @Time: 2021/6/14 17:31
# @File: 保存图片.py
# @Software: PyCharm
import pymysql

from index import get_html


def get_imgs():
    try:
        conn = pymysql.connect(host="localhost", user="root",
                               password="1234", db="b-video-stat", port=3306)
        cur = conn.cursor()
        sql = """
               select pic from ranks
           """

        cur.execute(sql)
        data = cur.fetchall()
        data = [d[0] for d in data]
        conn.commit()
        cur.close()
        conn.close()
        return data
    except Exception as e:
        print('出错了：', e)


def get_face_imgs():
    try:
        conn = pymysql.connect(host="localhost", user="root",
                               password="1234", db="b-video-stat", port=3306)
        cur = conn.cursor()
        sql = """
               select face from up_info
           """

        cur.execute(sql)
        data = cur.fetchall()
        data = [d[0] for d in data]
        conn.commit()
        cur.close()
        conn.close()
        return data
    except Exception as e:
        print('出错了：', e)


def get_imgs_sql(sql):
    try:
        conn = pymysql.connect(host="localhost", user="root",
                               password="1234", db="b-video-stat", port=3306)
        cur = conn.cursor()

        cur.execute(sql)
        data = cur.fetchall()
        data = [d[0] for d in data]
        conn.commit()
        cur.close()
        conn.close()
        return data
    except Exception as e:
        print('出错了：', e)


def main():
    # imgs = get_face_imgs()
    imgs = get_imgs_sql("select pic from up_word")
    dir = "./up_face_img/{}"
    print(imgs)
    count = 1
    total = len(imgs)
    for url in imgs:
        img = get_html(url, st=0.2).content
        with open(dir.format(url.split("/")[-1]), "wb") as f:
            f.write(img)
        print(count / total, "保存成功", url.split("/")[-1])
        count += 1


if __name__ == '__main__':
    main()
